package com.wish.nettywithpack;

import com.wish.common.MyUtils;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


/**
 * @author tantexian
 * @since 2016/7/11
 */
public class NettyRobotClientWithPack {

    public static void main(String[] args) {
        new NettyRobotClientWithPack().connect(MyUtils.getDefaultServerAddr(), MyUtils.getDefaultPort());
    }


    public void connect(String host, int port) {
        // 关于使用方式请参考NettyRobotServer注释
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 以换行符为结束符拆包粘包
                        /*socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new RobotClientHandle());*/

                        // 以$_END_$为结束符拆包粘包
                        // 自定义分隔符解析器，以$_作为分隔
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_END_$".getBytes());
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                        socketChannel.pipeline().addLast(new StringDecoder()); // 自动将接受到的对象转换为String
                        socketChannel.pipeline().addLast(new StringEncoder()); // 编码
                        socketChannel.pipeline().addLast(new RobotClientHandle());
                    }
                });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            channelFuture.channel().closeFuture().sync();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    class RobotClientHandle extends ChannelHandlerAdapter {

        private int count = 0;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {

            // String msg = "what is you name?\n"; // 此处为以\r or \r\n 为结束符
            String msg = "what is you name?" + "$_END_$"; // 此处为以 $_END_$ 为结束符
            for (int i = 0; i < 100; i++) {
                ctx.write(msg);

            }
            ctx.flush();
        }


        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String msgStr = (String) msg;
            System.out.println("[" + (++count) + "] " + msgStr);
        }


        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }

}
